# @Time : 2020/8/31 11:20
# @Author : Fioman 
# @Phone : 13149920693
import cv2 as cv
import numpy as np
import imutils

image = cv.imread("pic/23.png")
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
edged = cv.Canny(gray, 75, 200)
cv.imshow("Original", image)
cv.imshow("Edge Map", edged)
cv.waitKey(0)

cnts = cv.findContours(edged.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv.contourArea, reverse=True)[:7]

for c in cnts:
    perimeter = cv.arcLength(c, True)
    approx = cv.approxPolyDP(c, 0.01 * perimeter, True)
    print("Original : {},approx : {}".format(len(c), len(approx)))
    if len(approx) == 4:
        cv.drawContours(image, [approx], -1, (0, 255, 0), 2)

cv.imshow("Output", image)
cv.waitKey(0)

image = cv.imread("pic/24.png")
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
cnts = cv.findContours(gray.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cntsMax = sorted(cnts, key=cv.contourArea, reverse=True)[0]
perimeter = cv.arcLength(cntsMax, True)
approx = cv.approxPolyDP(cntsMax, 0.01 * perimeter, True)
print("len(approx) = {}".format(len(approx)))

approx2 = cv.approxPolyDP(cntsMax,0.05 * perimeter,True)
print("len(approx2) = {}".format(len(approx2)))

approx3 = cv.approxPolyDP(cntsMax,0.1 * perimeter,True)
print("len(approx3) = {}".format(len(approx3)))

